from aip import AipOcr
import  urllib.parse

""" 你的 APPID AK SK """
APP_ID = '16483053'
API_KEY = 'GrGCtPB9TlwG80xryG3r7bKw'
SECRET_KEY = '6laUBxCKoYNVGfU2LmqpYDGYN3TswfNp'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
# image="/Users/jiahongzheng/Downloads/报告test1.jpg "
""" 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


#
# """ 调用通用文字识别, 图片参数为本地图片 """
# client.basicGeneral(image);
#
# """ 如果有可选参数 """
# options = {}
# options["language_type"] = "CHN_ENG"
# options["detect_direction"] = "true"
# options["detect_language"] = "true"
# options["probability"] = "true"
#
# """ 带参数调用通用文字识别, 图片参数为本地图片 """
# res=client.basicGeneral(image, options)
# for item in res['words_result']:
#     print(item['words'])
import os
from PIL import Image

ext = ['jpg', 'jpeg', 'png']
files = os.listdir('.')


def process_image(filename, mwidth=1560, mheight=2080):
    image = Image.open(filename)
    w, h = image.size
    if w <= mwidth and h <= mheight:
        print(filename, 'is OK.')
        return
    if (1.0 * w / mwidth) > (1.0 * h / mheight):
        scale = 1.0 * w / mwidth
        new_im = image.resize((int(w / scale), int(h / scale)))

    else:
        scale = 1.0 * h / mheight
        new_im = image.resize((int(w / scale), int(h / scale)))
    new_im.save(filename)
    new_im.close()


for file in files:
    if file.split('.')[-1] in ext:
        process_image(file)
def get_ocr_result(filepath):
    process_image(filepath)
    # """ 调用通用文字识别, 图片参数为远程url图片 """
    # client.basicGeneralUrl(url);
    """ 如果有可选参数 """
    options = {}
    options["language_type"] = "CHN_ENG"
    options["detect_direction"] = "true"
    options["detect_language"] = "true"
    options["probability"] = "true"
    # """ 带参数调用通用文字识别, 图片参数为远程url图片 """
    # res=client.basicGeneralUrl(url, options)
    image = get_file_content(filepath)
    """ 调用通用文字识别, 图片参数为本地图片 """
    res=client.basicGeneral(image, options);

    return res['words_result']


# imgdata=""
# imgdata=urllib.parse.quote(imgdata).encode()
# file = open('1.png', 'wb')
# file.write(imgdata)
# file.close
# image = get_file_content('1.png')
# res=client.basicGeneral(image)
# for item in res['words_result']:
if __name__ == '__main__':
    process_image('D:\zjk\项目\healthy_me\main\OCR\example.jpeg')
    # print(get_ocr_result('D:\zjk\项目\healthy_me\main\OCR\example.jpeg'))